/* eslint-disable react/jsx-key */
import citycode from '@/assets/citycode.json';
import { SUCCESS_CODE } from '@/utils/request';
import { Drawer, message, Spin, Image } from 'antd';
import { useEffect, useState } from 'react';
import { getImage, getParkDetail } from '../service';
import styles from '../style.less';
import type { DetailItem } from '../types';
interface ParkProps {
  id: string;
  visible: boolean;
  onClose: () => void;
}

const STATUS_MAP = new Map().set(3, '车位不足').set(2, '车位紧张').set(1, '车位充足');

export default (props: ParkProps) => {
  const { visible, onClose, id } = props;
  const [parkDetails, setParkDetails] = useState<DetailItem>();
  const [loading, setLoading] = useState<boolean>(false);
  const [parkUrls, setParkUrls] = useState<string[]>();

  useEffect(() => {
    setLoading(true);
    getParkDetail(id).then((res) => {
      setLoading(false);
      if (res.code === SUCCESS_CODE) {
        setParkDetails(res.data);
        return true;
      }
      message.error('获取详情失败');
      return false;
    });
    getImage(id).then((res) => {
      if (res.code === SUCCESS_CODE) {
        setParkUrls(res.data);
        return true;
      }
      message.error('获取图片失败');
      return false;
    });
  }, [id]);

  const count = parkDetails?.space_total_count;

  const code = parkDetails?.city_code ? parkDetails?.city_code : 0;

  function getCity() {
    const district = citycode[code || ''];
    if (code == '') {
      return '无数据';
    }
    if (String(code).endsWith('0000')) {
      return `${district}`;
    } else if (!String(code).endsWith('0000') && String(code).endsWith('00')) {
      const province = citycode[parseInt(String(code / 10000)) * 10000];
      return `${province} ${district}`;
    } else if (!String(code).endsWith('0000') && !String(code).endsWith('00')) {
      const province = citycode[parseInt(String(code / 10000)) * 10000];
      const city1 = citycode[parseInt(String(code / 100)) * 100];
      return `${province} ${city1} ${district}`;
    }
    return;
  }

  return (
    <Drawer
      title="停车场详情"
      placement="right"
      width="500"
      onClose={() => {
        onClose();
      }}
      visible={visible}
    >
      <Spin spinning={loading}>
        <div className={styles.DrawerDetails}>
          <p>停车场名称：{parkDetails?.name}</p>
          <p>停车场编号：{parkDetails?.id}</p>
          <p>行政区：{getCity()}</p>
          <p>详细地址：{parkDetails?.address}</p>
          <p>泊位总数：{count >= 0 ? count : '-'}</p>
          <p>运营时间：{parkDetails?.open_time}</p>
          <p>计费规则：{parkDetails?.scheme.name}</p>
          <p>状态：{STATUS_MAP.get(parkDetails?.space_full_status)}</p>
          <p>
            图片：
            <p>
              {parkUrls?.map((item: string) => (
                <p>
                  <Image width="18vw" src={item} />
                </p>
              ))}
            </p>
          </p>
        </div>
      </Spin>
    </Drawer>
  );
};
